import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"
import { staticRoutes } from './route' // 展示在菜单中的路由
import { getRouterList } from './logic'
import { Session } from '@/utils/storage'
import { getToken } from "@/utils/token"
// 页面切换动画
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { PrevLoading } from '@/utils/loading.js';

// 解决 `element ui` 导航栏重复点菜单报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
}

Vue.use(VueRouter)

// 加载静态路由
const createRouter = () =>
    new VueRouter({
        routes: staticRoutes,
    })
// 创建路由
const router = createRouter();

// 加载 loading
PrevLoading.start()
// 路由加载前
router.beforeEach(async (to, from, next) => {
    NProgress.configure({ showSpinner: false });
    if (to.meta.title && to.path !== '/login') NProgress.start();
    let token = getToken()
    if (to.path === '/login' && !token) {
        NProgress.start()
        next()
        NProgress.done()
    } else {
        if (!token) {
            NProgress.start()
            next('/login')
            Session.clear()
            NProgress.done()
        } else if (token && to.path === '/login') {
            next('/home')
            NProgress.done()
        } else {
            if (Object.keys(store.state.routesList.routesList).length <= 0) {
                getRouterList(router, to, next);
            } else {
                next();
                NProgress.done()
            }
        }
    }
})

router.afterEach(() => {
    PrevLoading.done();
    NProgress.done();
})

// 导出路由
export default router;
